<template>
  <view class="tn-checkbox-group" :style="checkboxGroupStyle">
    <slot></slot>
  </view>
</template>

<script lang="ts" setup>
import { 
  checkboxGroupProps, 
  checkboxGroupEmits, 
  CheckboxGroupProps,
  checkboxGroupKey, 
  CheckboxGroupContext, 
  CheckboxModelValue, 
  CheckboxGroupModelValue
} from '../../../types/tn-checkbox'
import { ref, watch, reactive, toRefs, provide, computed, CSSProperties } from 'vue'
import { UPDATE_MODEL_EVENT } from '../../../constants'
import { useFormItem } from '../../tn-form/lib/hooks'

const props = defineProps(checkboxGroupProps)
const emits = defineEmits(checkboxGroupEmits)

const { formItem } = useFormItem()

// checkboxGroup对应样式
const checkboxGroupStyle = computed<CSSProperties>(() => {
  let style: CSSProperties = {}
  if (props.wrap) {
    style.flexDirection = 'column'
    style.alignItems = 'flex-start'
    style.justifyContent = 'center'
  }
  return style
})

// 选中选项的name
let activeName = ref<CheckboxGroupProps['modelValue']>([])

const setActiveName = (_activeName: CheckboxGroupModelValue) => {
  activeName.value = _activeName
  emits(UPDATE_MODEL_EVENT, activeName.value)
  emits('change', activeName.value)
  if (props?.validateEvent) {
    formItem?.validate?.('change').catch((err) => console.error(err))
  }
}

// 处理修改事件
const changeEvent: CheckboxGroupContext['changeEvent'] = (val: CheckboxModelValue) => {
  // 判断点击项是否已经存在，如果已经存在则移除否则添加
  const _activeName = activeName.value
  const index = _activeName.indexOf(val)
  if (index !== -1) {
    _activeName.splice(index, 1)
  } else {
    _activeName.push(val)
  }
  setActiveName(_activeName)
}

watch(() => props.modelValue, (val: CheckboxGroupProps['modelValue']) => {
  activeName.value = val
}, {
  immediate: true
})

provide(
  checkboxGroupKey,
  reactive({
    ...toRefs(props),
    activeName,
    changeEvent
  })
)
</script>

<script lang="ts">
export default {
  options: {
    // 在微信小程序中将组件节点渲染为虚拟节点，更加接近Vue组件的表现(不会出现shadow节点下再去创建元素)
    virtualHost: true
  }
}
</script>

<style lang="scss" scoped>

.tn-checkbox-group {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: center;
  justify-content: flex-start;
}
</style>
